package com.example.api.service.impl;

import com.example.api.dao.EmployeeDao;
import com.example.api.dao.WarehouseDao;
import com.example.api.model.entity.Employee;
import com.example.api.model.entity.Warehouse;
import com.example.api.model.support.RespBean;
import com.example.api.service.EmployeeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeDao employeeDao;

    @Resource
    private WarehouseDao warehouseDao;

    @Override
    public RespBean save(Employee employee) {
        employee.setCreateTime(new Date());
        if (employeeDao.insertSelective(employee) > 0) {
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @Override
    public RespBean update(Employee employee) {
        Employee oldEmployee = employeeDao.selectByPrimaryKey(employee.getId());
        Warehouse warehouse = warehouseDao.selectByPrimaryKey(oldEmployee.getDepartment());
        if (employee.getId().equals(warehouse.getEid()) && !employee.getDepartment().equals(oldEmployee.getDepartment())) {
            return RespBean.error("该员工为" + warehouse.getName() + "的仓库负责人，不可修改");
        }
        employee.setUpdateTime(new Date());
        if (employeeDao.updateByPrimaryKeySelective(employee) > 0) {
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @Override
    public RespBean delete(Integer id) {
        Employee employee = employeeDao.selectByPrimaryKey(id);
        if (employee.getDepartment() != null) {
            Warehouse warehouse = warehouseDao.selectByPrimaryKey(employee.getDepartment());
            if (id.equals(warehouse.getEid())) return RespBean.error("该员工为" + warehouse.getName() + "的仓库负责人，不可删除");
        }
        if (employeeDao.deleteByPrimaryKey(id) > 0) {
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @Override
    public Employee findById(Integer id) {
        return employeeDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> findAll(String name) {
        return employeeDao.findAll(name);
    }

    @Override
    public List<Employee> findByWarehouse() {
        return employeeDao.findByWarehouse();
    }

}